package com.hi.hiparty.service;

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import com.hi.hiparty.location.ILastLocationFinder;
import com.hi.hiparty.location.LegacyLastLocationFinder;
import com.hi.hiparty.location.PlacesConstants;
import com.hi.hiparty.ui.session.UserSessionManager;
import com.hi.hiparty.util.Constants;

public class LocationService extends Service implements ILocationService {

	private static final String TAG = "LocationService";

	private boolean stopFlag = false;

	private String latlng;

	private ServiceBinder serviceBinder = new ServiceBinder();

	public class ServiceBinder extends Binder implements ILocationService {

		@Override
		public String getLatlng() {
			return latlng;
		}

	}

	@Override
	public IBinder onBind(Intent intent) {
		return serviceBinder;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		Thread locationWatchThread = new LocationWatchThread();
		locationWatchThread.start();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		this.stopFlag = true;
		Log.v(TAG, "location service shut down");
	}

	private class LocationWatchThread extends Thread {

		private long interval = 5000;

		@Override
		public void run() {
			while (!stopFlag) {
				Log.v(TAG, "begin to fetch location");
				ILastLocationFinder lastLocationFinder = new LegacyLastLocationFinder(LocationService.this);
				lastLocationFinder.setChangedLocationListener(oneShotLastLocationUpdateListener);
				Location l = lastLocationFinder.getLastBestLocation(PlacesConstants.MAX_DISTANCE,
						System.currentTimeMillis() - PlacesConstants.MAX_TIME);
				if (null != l) {
					latlng = l.getLatitude() + "," + l.getLongitude();
					UserSessionManager.updateUserLocation(LocationService.this, l.getLatitude(), l.getLongitude());
					if (interval < Constants.MAX_LOCATION_REFRESH_INTERVAL) {
						interval += 5000;
					}
				}
				try {
					Thread.sleep(interval);
				} catch (InterruptedException e) {
					Log.w(TAG, e);
				}
			}
		}
	}

	protected LocationListener oneShotLastLocationUpdateListener = new LocationListener() {
		public void onLocationChanged(Location l) {
			if (null != l) {
				latlng = l.getLatitude() + "," + l.getLongitude();
			}
		}

		public void onProviderDisabled(String provider) {
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}

		public void onProviderEnabled(String provider) {
		}
	};

	@Override
	public String getLatlng() {
		return latlng;
	}

}
